package HW5;

import java.io.*;
import java.net.Socket;

public class MutliThread extends Thread {
    private Socket s;

    public MutliThread(Socket s ){
        this.s = s ;
    }

    @Override
    public void run(){

        BufferedReader br = null;
        PrintStream ps = null;
        File f = null;
        InputStream  is = null;
        FileOutputStream fs = null;
        try {
            //输入输出流进行通信
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            ps = new PrintStream(s.getOutputStream());
            f = new File("/Users/mac/Desktop/test3.txt");
            fs = new FileOutputStream(f);
            is = s.getInputStream();
            while (true) {

                String st = br.readLine();
                System.out.println("客户端" + s.getInetAddress().getHostName() + "发来:" + st);

                if("bye".equalsIgnoreCase(st)) {
                    System.out.println(s.getInetAddress().getHostName() + "下线了");
                    break;
                }
                out: if("upload".equals(st)){
                    //f = new File("/Users/mac/Desktop/test3.txt");
                    byte[] buf = new byte[1024];
                    int len = 0;
                    while ((len= is.read(buf))!=-1){
                        fs.write(buf,0,len);
                    }
                    System.out.println("收到文件，已经存为" + f.getName() + "位置在:" + f.getPath());
                    break out;
                }

                ps.println("收到");
                System.out.println("服务器发送数据成功");
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(null!=ps){
                ps.close();
            }
            if(null!=br){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=s){
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=fs){
                try {
                fs.close();
            } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
